import axios from 'axios'
import qs from 'qs';
import router from '../router'
import {
    Message
} from 'element-ui'
import {
    getToken,
    removeToken
} from '@/utils/cookie';

const instance = axios.create({
    // baseURL: 'http://www.resource.com/',
    baseURL: 'http://api.caryard.liguoqin.com/',
    timeout: 15000
})
instance.interceptors.request.use(
    config => {
        // config.headers['Content-Type'] = "application/json;charset=UTF-8";
        if (getToken()) {
            config.headers['token'] = getToken()
        }
        // config.data = qs.stringify(config.FormData);
        return config
    },
    error => {
        Promise.reject(error)
    }
)
instance.interceptors.response.use(
    response => {
        if (response.data.msg) {
            Message({
                message: response.data.msg,
                type: 'success',
                duration: 2000
            })
        }
        return response.data
    },
    error => {
        if (error.response) {
            // if (error.response.data.client_code == -3) {
            //     //token is not found
            //     removeToken();
            //     Message({
            //         message: error.response.data.msg,
            //         type: 'error',
            //         duration: 1000
            //     })
            //     setTimeout(function() {
            //         router.push({
            //             name: '登录',
            //         })
            //         return Promise.reject(error.response.data.msg)
            //     }, 1500)
            // } else
            if (error.response.data.client_code == -2) {
                //删除登录态
                removeToken();
                Message({
                    message: error.response.data.msg,
                    type: 'error',
                    duration: 1000
                })
                setTimeout(function() {
                    router.push({
                        path: '/login',
                    })
                    return Promise.reject(error.response.data.msg)
                }, 1500)
            } else if (error.response.data.client_code == -1) {
                //正常錯誤
            }
            if (error.response.data.msg) {
                Message({
                    message: error.response.data.msg,
                    type: 'error',
                    duration: 1500
                })
            }
            return Promise.reject(error.response.data.msg)
        } else if (error.request) {
            Message({
                message: '您所访问的资源无响应',
                type: 'error',
                duration: 1500
            })
        } else {
            // Something happened in setting up the request that triggered an Error
            console.log('设置有误，err:', error.message);
        }
        return Promise.reject(error)
    }
)

export default instance